import { useRef, useEffect } from 'react';

/**
 * 基础 IntersectionObserver Hook
 * 用于检测元素是否进入视口
 * @param {Function} callback - 当元素进入视口时调用的回调函数
 * @param {Object} options - IntersectionObserver 配置选项
 * @returns {React.RefObject} 需要观察的元素的 ref
 */
export const useIntersectionObserver = (callback, options = {}) => {
    const ref = useRef(null);
    
    useEffect(() => {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    callback(entry);
                }
            });
        }, options);
        
        if (ref.current) {
            observer.observe(ref.current);
        }
        
        return () => observer.disconnect();
    }, [callback, options]);
    
    return ref;
};

/**
 * 图片懒加载 Hook
 * 专门用于图片懒加载场景，自动处理图片加载和观察器清理
 * @param {string} src - 图片的 src 属性
 * @returns {React.RefObject} 图片元素的 ref
 */
export const useLazyImage = (src) => {
    const imgRef = useRef(null);
    
    useEffect(() => {
        const observer = new IntersectionObserver((entries, obs) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    const oImg = document.createElement('img');
                    oImg.src = img.dataset.src;
                    oImg.onload = function () {
                        img.src = img.dataset.src;
                    };
                    obs.unobserve(img);
                }
            });
        });
        
        if (imgRef.current) {
            observer.observe(imgRef.current);
        }
        
        return () => observer.disconnect();
    }, []);
    
    return imgRef;
};

/**
 * 无限滚动 Hook
 * 专门用于无限滚动场景，预设了适合的配置
 * @param {Function} onIntersect - 当元素进入视口时调用的回调函数
 * @returns {React.RefObject} 需要观察的元素的 ref
 */
export const useInfiniteScroll = (onIntersect) => {
    return useIntersectionObserver((entry) => {
        if (entry.isIntersecting) {
            onIntersect();
        }
    });
};